<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <title>教练合作费结算</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .report-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .report-subtitle {
            font-size: 18px;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0 10px 0;
            color: #333;
        }
        .total-row {
            font-weight: bold;
            background-color: #f5f5f5;
        }
        .date-input {
            margin: 20px 0;
            padding: 8px;
        }
        .hidden {
            display: none;
        }
        #export-report-title {
            display: none;
        }
    </style>
</head>
<body>
    {% include 'show_ins_info.html' %}
    
    

    <div>
        <label for="month-input">选择月份: </label>
        <input type="month" id="month-input" class="date-input">       
    </div>

    <div>
        <label for="ins-select">选择教练: </label>
        <select id="ins-select" class="date-input">
            <option value="">--请选择教练--</option>
            <!-- 教练列表将通过JavaScript动态加载 -->
        </select>
    </div>

    <div style="margin-top: 20px;">
        <button id="get-report-btn" style="padding: 8px 16px;">获取报表</button>
        <button id="export-pdf-btn" style="padding: 8px 16px; margin-left: 10px;">导出PDF</button>
        <button id="export-jpg-btn" style="padding: 8px 16px; margin-left: 10px;">导出JPG</button>
    </div>

    <div class="header">
        <div class="report-title" id="report-title">教练合作费用结算</div>
    </div>

    <div id="result-container" class="hidden">
        <!-- 新增的导出专用标题 -->
        <div class="header">
            <div class="report-title" id="export-report-title">教练合作费用结算</div>
        </div>
        <!-- 基本合作咨询费 -->
        <p id="basic-salary-container" style="display:none;">
            <span class='section-title' >· 基本合作咨询费：</span><strong><span id="basic-salary">0.00</span></strong>元
            <span id="basic-comment"></span>
        </p>

        <!-- 私教课详情 -->
        <div id="private-class-section" style="display:none;">
            <div class="section-title">· 私教课合作提成详情</div>
            <table id="private-class-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>购课日期</th>
                        <th>卡号</th>
                        <th>会员姓名</th>
                        <th>课程类型</th>
                        <th>课程名称</th>
                        <th>上课时（节）数</th>
                        <th>应收金额（元）</th>
                        <th>实收金额（元）</th>
                        <th>单节课价格（元）</th>
                        <th>合作课时费（元）</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p> - 私教课合作提成总计：<strong><span id="private-total">0.00</span></strong>元</p>
        </div>

        <!-- 小团课详情 -->
        <div id="group-class-section" style="display:none;">
            <div class="section-title">· 小团课合作提成详情</div>
            <table id="group-class-table">
                <thead>
                    <tr>
                        <th>上课日期</th>
                        <th>会员</th>
                        <th>课程类型</th>
                        <th>课程名称</th>
                        <th>课时数（节）</th>
                        <th>合作课时费（元）</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p> - 小团课合作提成总计：<strong><span id="group-total">0.00</span></strong>元</p>
        </div>

        <!-- 未结算课程详情 -->
        <div id="unsettled-section" style="display:none;">
            <div class="section-title">· 未结算课程清单</div>
            <table id="unsettled-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>购课日期</th>
                        <th>卡号</th>
                        <th>会员姓名</th>
                        <th>课程类型</th>
                        <th>课程名称</th>
                        <th>开始日期</th>
                        <th>本月末距课程开始天数</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p id="no-unsettled" style="display:none;padding-left:10px;">无</p>
        </div>

        <!-- 销售详情 -->
        <div id="sales-section" style="display:none;">
            <div class="section-title">· 合作销售提成</div>
            <table id="sales-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>购课日期</th>
                        <th>卡号</th>
                        <th>会员姓名</th>
                        <th>应收金额（元）</th>
                        <th>实收金额（元）</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p> - 销售金额总计：<span id="sales-amount-total">0.00</span>元</p>
            <p> - 合作销售提成总计：<strong><span id="sales-total">0.00</span></strong>元</p>
            <p> - 销售区间：<span id="sales-range">[0-15000) : 0</span></p>
        </div>

        <!-- 其他情况 -->
        <div id="other-section" style="display: none; margin-top: 15px;">
            <div class="section-title">· 其他情况</div>
            <p style="white-space: pre-line;padding-left:20px;"></p>
            <p style="padding-left:20px;">涉及金额: <span id="other-amount">0.00</span> 元</p>
        </div>

        <!-- 总计 -->
        <div class="section-title">合作费用总计</div>
        <div class="summary">
            <p><strong>总计金额：<span id="grand-total">0.00</span>元</strong></p>
        </div>
    </div>

    <script src="../static/js/common.js"></script>
<script src="/static/js/jspdf.umd.min.js"></script>
<script src="/static/js/html2canvas.min.js"></script>
    <script>
        let insList;
        let insId;
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // loginCheck();

            //增加返回上一页按钮
            addGoLastPageBtn();

            selectToday('month-input', 'month');
            
            let params;
            let salaryParams = {};
            // let data_ins = []; // 存储教练详细信息

            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            console.log('ins_id:',insId)
            
            // 加载教练列表
            fetch('/get_all_ins_list')
                .then(response => response.json())
                .then(data => {
                    const insList = data['ins_list'];
                    const insSelect = document.getElementById('ins-select');
                    insList.forEach(ins => {
                        const option = document.createElement('option');
                        option.value = ins.slice(0,8);
                        option.textContent = ins.slice(8);
                        insSelect.appendChild(option);
                    });
                    // 设置默认选中陆伟杰
                    insSelect.value = 'LZINS001';
                    
                    // 添加日期和教练选择变化事件监听
                    document.getElementById('month-input').addEventListener('change', function() {
                        document.getElementById('result-container').classList.add('hidden');
                        document.getElementById('report-title').textContent = '教练合作费用结算';
                        document.getElementById('export-report-title').textContent = '教练合作费用结算';
                    });
                    
                    insSelect.addEventListener('change', function() {
                        document.getElementById('result-container').classList.add('hidden');
                        document.getElementById('report-title').textContent = '教练合作费用结算';
                        document.getElementById('export-report-title').textContent = '教练合作费用结算';
                    });
                })
                .catch(error => console.error('Error:', error));   

            fetch('/get_salary_params', {
                method: 'GET',
                })
                .then(response => response.json())
                .then(data => {
                    console.log('salary params:', data);
                    salaryParams = data;
                })
                .catch(error => console.error('Error:', error));    

            // 获取报表按钮点击事件
            document.getElementById('get-report-btn').addEventListener('click', function() {
                const month = document.getElementById('month-input').value;
                const insId = document.getElementById('ins-select').value;

                if (!month || !insId) {
                    alert('请选择月份和教练');
                    return;
                }

                fetch('/get_ins_salary_report', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        month: month,
                        ins_id: insId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    console.log('API response:', data); // 调试日志
                    if(data.res === 'ok') {
                        if (data.data) {
                            renderReport(data.data);
                            document.getElementById('result-container').classList.remove('hidden');
                        } else {
                            alert('报表数据为空');
                        }
                    } else {
                        alert('获取报表失败: ' + (data.error || '未知错误'));
                    }
                })
                .catch(error => {
                    alert('获取报表失败，请稍后重试');
                });
            });

            // 渲染报表数据
            function renderReport(reportData) {
                console.log('Received report data:', reportData); // 调试日志
                
                // 检查数据是否存在
                if (!reportData || typeof reportData !== 'object') {
                    console.error('Invalid report data');
                    return;
                }

                // 隐藏report-title，显示export-report-title
                document.getElementById('report-title').style.display = 'none';
                document.getElementById('export-report-title').style.display = 'block';

                // 渲染基本信息
                const reportTitle = `${reportData.month} ${reportData.ins_name}教练合作费用结算`;
                document.getElementById('report-title').textContent = reportTitle;
                document.getElementById('export-report-title').textContent = reportTitle;
                document.getElementById('export-report-title').textContent = reportTitle;
                
                const basicSalaryContainer = document.getElementById('basic-salary-container');
                if (reportData.basic_salary && reportData.basic_salary > 0) {
                    document.getElementById('basic-salary').textContent = reportData.basic_salary.toFixed(2);
                    document.getElementById('basic-comment').textContent = reportData.basic_comment ? `${reportData.basic_comment}` : '';
                    basicSalaryContainer.style.display = 'block';
                } else {
                    basicSalaryContainer.style.display = 'none';
                }

                // 渲染私教课详情
                const privateSection = document.getElementById('private-class-section');
                if (reportData.private_class_details && Array.isArray(reportData.private_class_details) && reportData.private_class_details.length > 0) {
                    const privateTbody = document.querySelector('#private-class-table tbody');
                    privateTbody.innerHTML = '';
                    reportData.private_class_details.forEach((item, index) => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td>${item.buy_date || ''}</td>
                            <td>${item.card_id || ''}</td>
                            <td>${item.cus_name || ''}</td>
                            <td>${item.class_type || ''}</td>
                            <td>${item.class_name || ''}</td>
                        <td>${item.class_count || 0}</td>
                        <td>${item.pay ? parseFloat(item.pay).toFixed(2) : '0.00'}</td>
                        <td>${item.real_pay ? parseFloat(item.real_pay).toFixed(2) : '0.00'}</td>
                        <td>${item.per_class_price ? parseFloat(item.per_class_price).toFixed(2) : '0.00'}</td>
                        <td>${item.commission ? parseFloat(item.commission).toFixed(2) : '0.00'}</td>
                        <td>${item.remark || ''}</td>
                        `;
                        privateTbody.appendChild(row);
                    });
                    document.getElementById('private-total').textContent = 
                        reportData.private_class_total ? reportData.private_class_total.toFixed(2) : '0.00';
                    privateSection.style.display = 'block';
                } else {
                    privateSection.style.display = 'none';
                }

                // 渲染小团课详情
                const groupSection = document.getElementById('group-class-section');
                if (reportData.group_class_details && Array.isArray(reportData.group_class_details) && reportData.group_class_details.length > 0) {
                    const groupTbody = document.querySelector('#group-class-table tbody');
                    groupTbody.innerHTML = '';
                    reportData.group_class_details.forEach(item => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${item.cls_time || ''}</td>
                            <td>${item.member || ''}</td>
                            <td>${item.class_type || ''}</td>
                            <td>${item.class_name || ''}</td>
                            <td>${item.cls_count || 0}</td>
                            <td>${item.commission|| 0}</td>
                        `;
                        groupTbody.appendChild(row);
                    });
                    document.getElementById('group-total').textContent = 
                        reportData.group_class_total ? reportData.group_class_total.toFixed(2) : '0.00';
                    groupSection.style.display = 'block';
                } else {
                    groupSection.style.display = 'none';
                }

                // 渲染销售详情
                const salesSection = document.getElementById('sales-section');
                if (reportData.sales_details && Array.isArray(reportData.sales_details) && reportData.sales_details.length > 0) {
                    const salesTbody = document.querySelector('#sales-table tbody');
                    salesTbody.innerHTML = '';
                    reportData.sales_details.forEach((item, index) => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td>${item.buy_date || ''}</td>
                            <td>${item.card_id || ''}</td>
                            <td>${item.cus_name || ''}</td>
                            <td>${item.pay_amount ? item.pay_amount.toFixed(2) : '0.00'}</td>
                            <td>${item.real_pay ? item.real_pay.toFixed(2) : '0.00'}</td>
                        `;
                        salesTbody.appendChild(row);
                    });
                    // 计算销售金额总和
                    let salesAmountTotal = 0;
                    reportData.sales_details.forEach(item => {
                        salesAmountTotal += item.pay_amount || 0;
                    });
                    document.getElementById('sales-amount-total').textContent = salesAmountTotal.toFixed(2);
                    document.getElementById('sales-total').textContent = 
                        reportData.sales_total ? reportData.sales_total.toFixed(2) : '0.00';
                    
                    // 计算并显示销售区间
                    // let salesRangeText = '';
                    // if (salaryParams && salaryParams.销提) {
                    //     const salesAmount = salesAmountTotal;
                    //     for (const [range, rate] of Object.entries(salaryParams.销提)) {
                    //         const rangeParts = range.match(/\[(\d+)-(\d+)\)/);
                    //         if (rangeParts) {
                    //             const min = parseInt(rangeParts[1]);
                    //             const max = parseInt(rangeParts[2]);
                    //             if (salesAmount >= min && (max === 0 || salesAmount < max)) {
                    //                 salesRangeText = `${range} : ${(rate * 100).toFixed(0)}%`;
                    //                 break;
                    //             }
                    //         }
                    //     }
                    // }
                    document.getElementById('sales-range').textContent =  reportData.sales_range || '[0-15000) : 0';
                    salesSection.style.display = 'block';
                } else {
                    salesSection.style.display = 'none';
                }

                // 渲染未结算课程详情
                const unsettledSection = document.getElementById('unsettled-section');
                const unsettledTable = document.getElementById('unsettled-table');
                const noUnsettled = document.getElementById('no-unsettled');
                
                if (reportData.unsettled_details && Array.isArray(reportData.unsettled_details) && reportData.unsettled_details.length > 0) {
                    const unsettledTbody = document.querySelector('#unsettled-table tbody');
                    unsettledTbody.innerHTML = '';
                    reportData.unsettled_details.forEach((item, index) => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td>${item.buy_date || ''}</td>
                            <td>${item.card_id || ''}</td>
                            <td>${item.cus_name || ''}</td>
                            <td>${item.cls_type || ''}</td>
                            <td>${item.cls_name || ''}</td>
                            <td>${item.start_date || ''}</td>
                            <td>${item.days_since_start || ''}</td>
                        `;
                        unsettledTbody.appendChild(row);
                    });
                    unsettledSection.style.display = 'block';
                    unsettledTable.style.display = 'table';
                    noUnsettled.style.display = 'none';
                } else {
                    unsettledSection.style.display = 'block';
                    unsettledTable.style.display = 'none';
                    noUnsettled.style.display = 'block';
                }

                // 渲染其他情况
                const otherSection = document.getElementById('other-section');
                if (reportData.other_remarks || parseFloat(reportData.other_amount)!==0) {
                    const otherRemarks = document.querySelector('#other-section p');
                    if (reportData.other_remarks) {
                        // 保留换行符并替换为<br>标签
                        otherRemarks.innerHTML = reportData.other_remarks.replace(/\n/g, '<br>');
                        otherRemarks.style.display = 'block';
                    } else {
                        otherRemarks.style.display = 'none';
                    }
                    document.getElementById('other-amount').textContent = 
                        reportData.other_amount ? parseFloat(reportData.other_amount).toFixed(2) : '0.00';
                    otherSection.style.display = 'block';
                } else {
                    otherSection.style.display = 'none';
                }

                // 渲染总计
                document.getElementById('grand-total').textContent = 
                    reportData.total ? reportData.total.toFixed(2) : '0.00';
                
                // 显示report-title，隐藏export-report-title
                document.getElementById('report-title').style.display = 'block';
                document.getElementById('export-report-title').style.display = 'none';
            }

        // 导出PDF功能
        document.getElementById('export-pdf-btn').addEventListener('click', function() {
            if (document.getElementById('result-container').classList.contains('hidden')) {
                alert('请先生成报表');
                return;
            }

            const { jsPDF } = window.jspdf;
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.getElementById('result-container');
            
            // 显示导出专用标题
            document.getElementById('export-report-title').style.display = 'block';
            
            html2canvas(element, {
                scale: 2,
                logging: false,
                useCORS: true,
                allowTaint: true
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = doc.internal.pageSize.getWidth() - 40;
                const imgHeight = canvas.height * imgWidth / canvas.width;
                
                doc.addImage(imgData, 'PNG', 20, 20, imgWidth, imgHeight);
                doc.save(`${document.getElementById('report-title').textContent}.pdf`);
                
                // 导出完成后隐藏专用标题
                document.getElementById('export-report-title').style.display = 'none';
            });
        });

        // 导出JPG功能
        document.getElementById('export-jpg-btn').addEventListener('click', function() {
            if (document.getElementById('result-container').classList.contains('hidden')) {
                alert('请先生成报表');
                return;
            }

            const element = document.getElementById('result-container');
            
            // 显示导出专用标题
            document.getElementById('export-report-title').style.display = 'block';
            
            // Create temporary wrapper with padding
            const wrapper = document.createElement('div');
            wrapper.style.padding = '40px';
            wrapper.style.backgroundColor = '#ffffff';
            wrapper.style.width = 'fit-content';
            wrapper.appendChild(element.cloneNode(true));
            document.body.appendChild(wrapper);

            html2canvas(wrapper, {
                scale: 3,
                logging: false,
                useCORS: true,
                allowTaint: true,
                backgroundColor: '#ffffff',
                scrollX: 0,
                scrollY: 0
            }).then(canvas => {
                // Remove temporary wrapper
                document.body.removeChild(wrapper);
                const link = document.createElement('a');
                link.download = `${document.getElementById('report-title').textContent}.jpg`;
                link.href = canvas.toDataURL('image/jpeg');
                link.click();
                
                // 导出完成后隐藏专用标题
                document.getElementById('export-report-title').style.display = 'none';
            });
        });
    });
    </script>
</body>
</html>
